import 'dart:async';

import 'package:flutter_nb_net/flutter_net.dart';
import 'package:tracker/common/model/base_resp.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:tracker/pages/home/phone_book/model/contact_list_resp.dart';

part 'phone_book_repository.g.dart';

class PhoneBookRepository {
  PhoneBookRepositoryRef ref;

  PhoneBookRepository({required this.ref});

  /// 获取联系人列表
  FutureOr<List<Contact>> getContactList({required String imei}) async {
    var data = {
      'imei': imei,
    };
    var res = await get<ContactListResp, ContactListResp>('/contact/list',
        queryParameters: data, decodeType: ContactListResp());
    return res.when(
      success: (resp) => resp.data ?? <Contact>[],
      failure: (String msg, int code) {
        return Future.error(msg);
      },
    );
  }

  FutureOr<BaseResp> submit({required String imei, required List<Contact> contactList}) async {
    var data = {
      'imei': imei,
      'contactList': contactList,
    };
    final res = await post<BaseResp, BaseResp>('/contact/sendCommand', data: data, decodeType: BaseResp());
    return res.when(
      success: (resp) => resp,
      failure: (String msg, int code) {
        return Future.error(msg);
      },
    );
  }
}

@riverpod
PhoneBookRepository phoneBookRepository(PhoneBookRepositoryRef ref) => PhoneBookRepository(ref: ref);
